package cn.com.lms.business.exam.service;

import cn.com.lms.business.exam.persistence.entity.QuestionSubject;
import cn.com.lms.business.exam.persistence.entity.QuestionSubjectAnswer;
import cn.com.lms.business.exam.persistence.repository.QuestionSubjectAnswerRepository;

import com.bnzj.core.persistence.BaseService;

import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class QuestionSubjectAnswerService extends BaseService<QuestionSubjectAnswerRepository, QuestionSubjectAnswer,Long> {


    public Optional<QuestionSubjectAnswer> findBySubjectId(Long subjectId) {
        QuestionSubjectAnswer questionSubjectAnswer=new QuestionSubjectAnswer();
        questionSubjectAnswer.setSubjectId(subjectId);
        return super.findOne(questionSubjectAnswer);
    }


    public void saveOrUpdate(QuestionSubject questionSubject,String answer) {
        Optional<QuestionSubjectAnswer> opt = findBySubjectId(questionSubject.getId());
        if (opt.isPresent()) {
            QuestionSubjectAnswer target = opt.get();
            target.setAnswer(answer);
            if(questionSubject.getParse()!=null) {
                target.setParse(questionSubject.getParse());
            }
            super.save(target);
        } else {
            QuestionSubjectAnswer questionSubjectAnswer = new QuestionSubjectAnswer();
            questionSubjectAnswer.setAnswer(answer);
            questionSubjectAnswer.setParse(questionSubject.getParse());
            questionSubjectAnswer.setSubjectId(questionSubject.getId());
            questionSubjectAnswer.setCreator(questionSubject.getCreator());
            questionSubjectAnswer.setCreateTime(questionSubject.getCreateTime());
            questionSubjectAnswer.setCreatorName(questionSubject.getCreatorName());
            super.save(questionSubjectAnswer);
        }
    }
}
